package com.itheima.itheima_health.service.Impl;

import com.itheima.itheima_health.mapper.PermissionMapper;
import com.itheima.itheima_health.mapper.RoleMapper;
import com.itheima.itheima_health.mapper.UserMapper;
import com.itheima.itheima_health.pojo.Permission;
import com.itheima.itheima_health.pojo.Role;
import com.itheima.itheima_health.pojo.User;
import com.itheima.itheima_health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service
@Transactional
public class UserServiecImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    //根据用户名查询数据库获取用户信息和关联的角色信息,同时需要查询角色关联的权限信息
    public User findByUsername(String username) {
        //查询用户基本信息,不包含用户的角色
        User user = userMapper.findByUsername(username);
        if(user == null){
            return null;
        }
        Integer userId = user.getId();
        //根据用户id查询角色
        Set<Role> roles = roleMapper.findByUserId(userId);
        if(roles != null && roles.size() > 0){
            for(Role role : roles){
                Integer roleId = role.getId();
                //根据角色id查询关联的权限
                Set<Permission> permissions = permissionMapper.findByRoleId(roleId);
                if(permissions != null && permissions.size() > 0){
                    //让角色关联权限
                    role.setPermissions(permissions);
                }
            }
            //让用户关联角色
            user.setRoles(roles);
        }
        return user;
    }
}
